package com.zzyl.nursing.ws;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson2.JSON;
import com.zzyl.nursing.domain.AlertData;
import com.zzyl.nursing.domain.AlertRule;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.vo.AlertNotifyVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Component
@ServerEndpoint("/ws/{sid}")
public class WebSocketServer {

    private static Map<String,Session> sessionMap = new HashMap<>();

    /**
     * 连接建立时触发
     * @param session
     * @param sid
     */
    @OnOpen
    public void onOpen(Session session , @PathParam("sid") String sid) {
        log.info("有客户端连接到了服务器 , {}", sid);
        sessionMap.put(sid, session);
    }

    /**
     * 服务端接收到消息时触发
     * @param session
     * @param message
     * @param sid
     */
    @OnMessage
    public void onMessage(Session session , String message, @PathParam("sid") String sid) {
        log.info("接收到了客户端 {} 发来的消息 : {}", sid ,message);
    }

    /**
     * 连接关闭时触发
     * @param session
     * @param sid
     */
    @OnClose
    public void onClose(Session session , @PathParam("sid") String sid) {
        System.out.println("连接断开:" + sid);
        sessionMap.remove(sid);
    }

    /**
     * 通信发生错误时触发
     * @param session
     * @param sid
     * @param throwable
     */
    @OnError
    public void onError(Session session , @PathParam("sid") String sid , Throwable throwable) {
        System.out.println("出现错误:" + sid);
        throwable.printStackTrace();
    }

    /**
     * 广播消息
     * @param message
     * @throws IOException
     */
    public void sendMessageToAll(String message) throws IOException {
        Collection<Session> sessions = sessionMap.values();
        if(!CollectionUtils.isEmpty(sessions)) {
            for (Session session : sessions) {
                // 服务器向客户端发送消息
                session.getBasicRemote().sendText(message);
            }
        }
    }


    /**
     * 指定用户发送消息
     * @param userIds
     * @param data
     */
    public void sendMessageToHandler(List<Long> userIds, DeviceData data, AlertRule  rule) {
        if (CollUtil.isEmpty(userIds)){
            log.info("没有需要推送的用户");
            return;
        }
        for (Long userId : userIds) {
            log.info("开始推送用户 {} 的消息", userId);
            Session session = sessionMap.get(userId.toString());
            if (session != null) {
                AlertNotifyVo alertNotifyVo = AlertNotifyVo.builder()
                        .id(data.getId())
                        .accessLocation(data.getAccessLocation())
                        .locationType(data.getLocationType())
                        .physicalLocationType(data.getPhysicalLocationType())
                        .deviceDescription(data.getDeviceDescription())
                        .productName(data.getProductName())
                        .functionName(data.getFunctionId())
                        .dataValue(data.getDataValue())
                        .alertDataType(rule.getAlertDataType())
                        .voiceNotifyStatus(1)
                        .notifyType(1)
                        .isAllConsumer(false)
                        .build();
                try {
                    log.info("开始推送用户 {} 的消息", userId);
                    session.getBasicRemote().sendText(JSON.toJSONString(alertNotifyVo));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}